//
//  UIimage+Watermark.swift
//  App
//
//  Created by 红军张 on 16/9/12.
//  Copyright © 2016年 IndependentRegiment. All rights reserved.
//

import Foundation
import AssetsLibrary
import UIKit
import Photos

class PHAssetModels {
    var adress: String = ""
    var original: UIImage?
    var thumbnail: UIImage?
}

extension UIImage {
    
    //水印位置枚举
    enum WaterMarkCorner{
        case topLeft
        case topRight
        case bottomLeft
        case bottomRight
    }
    
    //添加水印方法
    func waterMarkedImage(_ waterMarkText:String, corner:WaterMarkCorner = .bottomRight,
                          margin:CGPoint = CGPoint(x: 20, y: 20),
                          waterMarkTextColor:UIColor = UIColor.white,
                          waterMarkTextFont:UIFont = UIFont.systemFont(ofSize: 20),
                          backgroundColor:UIColor = UIColor.clear) -> UIImage{
        
        let textAttributes = [NSAttributedString.Key.foregroundColor:waterMarkTextColor,
                              NSAttributedString.Key.font:waterMarkTextFont,
                              NSAttributedString.Key.backgroundColor:backgroundColor]
        let textSize = NSString(string: waterMarkText).size(withAttributes: textAttributes)
        var textFrame = CGRect(x: 0, y: 0, width: textSize.width, height: textSize.height)
        
        let imageSize = self.size
        switch corner{
        case .topLeft:
            textFrame.origin = margin
        case .topRight:
            textFrame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x, y: margin.y)
        case .bottomLeft:
            textFrame.origin = CGPoint(x: margin.x, y: imageSize.height - textSize.height - margin.y)
        case .bottomRight:
            textFrame.origin = CGPoint(x: imageSize.width - textSize.width - margin.x,
                                       y: imageSize.height - textSize.height - margin.y)
        }
        
        // 开始给图片添加文字水印
        UIGraphicsBeginImageContext(imageSize)
        self.draw(in: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
        NSString(string: waterMarkText).draw(in: textFrame, withAttributes: textAttributes)
        
        let waterMarkedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return waterMarkedImage!
    }
    
    func zz_normalizedImage() -> UIImage {
        if imageOrientation == .up {
            return self
        }
        
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(in: CGRect(origin: CGPoint.zero, size: size))
        let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return normalizedImage!;
    }
    

    //水印位置枚举
    enum PHAssetType{
        case Save
        case original
        case thumbnail
    }
    
    //通过标志符获取对应的资源
    func getPHAssetObject(localId: String) -> PHAsset {
        
        let assetResult = PHAsset.fetchAssets(
            withLocalIdentifiers: [localId], options: nil)
        let asset = assetResult[0]
        return asset
    }
    
    //    MARK: -- PHAsset操作  保存、读取
    func saveImageToPHAsset(type: PHAssetType ,callBack: @escaping (PHAssetModels?)->Void) {
        var localId = ""
        PHPhotoLibrary.shared().performChanges({
            let result = PHAssetChangeRequest.creationRequestForAsset(from: self)
            let assetPlaceholder = result.placeholderForCreatedAsset
            //保存标志符
            localId = assetPlaceholder?.localIdentifier ?? "notLocalIdentifier"
        }) { (isSuccess: Bool, error: Error?) in
            if isSuccess {
                print("保存成功!")
                //通过标志符获取对应的资源
                let asset = self.getPHAssetObject(localId: localId)
                
                let options = PHContentEditingInputRequestOptions()
                options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData)
                    -> Bool in
                    return true
                }
                
                switch type {
                case .Save:
                    //获取保存的图片路径
                    asset.requestContentEditingInput(with: options, completionHandler: {
                        (contentEditingInput:PHContentEditingInput?, info: [AnyHashable : Any]) in
                        print("地址：",contentEditingInput!.fullSizeImageURL!)
                        let obj = PHAssetModels()
                        obj.adress = (contentEditingInput!.fullSizeImageURL?.absoluteString)!
                        callBack(obj)
                    })
                case .original:
                    //获取保存的原图
                    PHImageManager.default().requestImage(for: asset,
                                                          targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit,
                                                          options: nil, resultHandler: { (image, _:[AnyHashable : Any]?) in
                                                            print("获取原图成功：\(String(describing: image))")
                                                            let obj = PHAssetModels()
                                                            obj.original = image
                                                            callBack(obj)
                    })
                    
                default :
                    //获取保存的缩略图
                    PHImageManager.default().requestImage(for: asset,
                                                          targetSize: CGSize(width:100, height:100), contentMode: .aspectFit,
                                                          options: nil, resultHandler: { (image, _:[AnyHashable : Any]?) in
                                                            print("获取缩略图成功：\(String(describing: image))")
                                                            let obj = PHAssetModels()
                                                            obj.thumbnail = image
                                                            callBack(obj)
                                                            
                    })
                }
            } else {
                print("保存失败：", error!.localizedDescription)
                callBack(nil)
            }
        }
    }

}


